﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace EffiProz.Core.Lib.Tar
{
    /**
    * Pax Interchange Format object constituted from an Input Stream.
    * <P/>
    * Right now, the only Pax property that we support directly is "size".
    */
    class PIFData : HashMap
    {
        private static Regex pifRecordPattern = new Regex("\\d+ +([^=]+)=(.*)");

        /**
         * N.b. this is nothing to do with HashMap.size() or Map.size().
         * This returns the value of the Pax "size" property.
         */
        public long? getSize()
        {
            return sizeObject;
        }

        private long? sizeObject = null;

        public PIFData(Stream stream)
        {

            try
            {
                StreamReader br =
                    new StreamReader(stream, Encoding.UTF8);
                String s, k, v;
                Match m;
                int lineNum = 0;

                /*
                 * Pax spec does not allow for blank lines, ignored white space,
                 * nor comments of any type, in the file.
                 */
                while ((s = br.ReadLine()) != null)
                {
                    lineNum++;

                    m = pifRecordPattern.Match(s);

                    if (!m.Success)
                    {
                        throw new TarMalformatException(
                            RB.singleton.getString(RB.PIF_MALFORMAT, lineNum, s));
                    }

                    k = m.Groups[1].Value;
                    v = m.Groups[2].Value;

                    if (v == null || v.Length < 1)
                    {
                        remove(k);
                    }
                    else
                    {
                        put(k, v);
                    }
                }
            }
            finally
            {
                stream.Close();
            }

            String sizeString = (String)get("size");

            if (sizeString != null)
            {
                try
                {
                    sizeObject = long.Parse(sizeString);
                }
                catch (FormatException )
                {
                    throw new TarMalformatException(
                        RB.singleton.getString(RB.PIF_MALFORMAT_SIZE, sizeString));
                }
            }
        }
    }
}
